<template>
	<div class="flex flex-col w-full h-full bg-white dark:bg-gray-800 rounded-xl border border-gray-100 dark:border-gray-700 shadow-md">
		<div class="flex justify-between items-center px-5 py-4 border-b border-gray-100 dark:border-gray-700">
			<h3 class="text-base font-semibold text-gray-800 dark:text-gray-200">{{ title }}</h3>
			<div>
				<slot name="header-actions">
					<el-button class="hover:bg-gray-50" icon="Refresh" size="small" circle @click="refreshHistory" :loading="loading"></el-button>
				</slot>
			</div>
		</div>
		<div class="overflow-y-auto flex-grow p-4">
			<div v-if="loading && !historyItems.length" class="flex justify-center items-center py-10">
				<el-icon class="text-blue-500 animate-spin" size="28"><Loading /></el-icon>
			</div>
			<div v-else-if="!historyItems.length" class="py-10 text-sm text-center text-gray-500 dark:text-gray-400">{{ emptyText }}</div>
			<div v-else class="history-container" style="height: calc(100% - 10px); display: flex; flex-direction: column">
				<el-table
					:data="historyItems"
					style="width: 100%; flex: 1"
					v-loading="loading"
					size="small"
					:cell-style="{ padding: '10px', cursor: 'pointer' }"
					highlight-current-row
					class="overflow-hidden rounded-lg border border-gray-100 dark:border-gray-700 history-table"
					@row-dblclick="handleItemClick"
				>
					<!-- Status column -->
					<el-table-column prop="materialStatus" label="状态" width="80" show-overflow-tooltip v-if="showStatusColumn"> </el-table-column>

					<!-- Prompt column -->
					<el-table-column prop="prompt" label="提示词" min-width="100" show-overflow-tooltip> </el-table-column>

					<!-- Creation time column, if available -->
					<el-table-column prop="createTime" label="创建时间" width="150" show-overflow-tooltip v-if="showTimeColumn"> </el-table-column>

					<!-- Actions column -->
					<el-table-column label="操作" width="60" fixed="right">
						<template #default="{ row }">
							<div class="flex space-x-2">
								<el-button
									v-if="materialType === 'Video' && (row.materialStatus === 'InProgress' || row.materialStatus === 'InQueue')"
									size="small"
									type="primary"
									circle
									class="!bg-blue-500 hover:!bg-blue-600"
									@click.stop="handleRefreshStatus(row)"
									:loading="row.refreshing"
								>
									<el-icon><RefreshRight /></el-icon>
								</el-button>
								<el-button
									size="small"
									type="danger"
									class="!bg-red-500 hover:!bg-red-600"
									icon="Delete"
									circle
									@click.stop="handleDelete(row)"
									:loading="row.deleting"
								></el-button>
							</div>
						</template>
					</el-table-column>
				</el-table>

				<!-- 内置分页组件 -->
				<div class="mt-4" v-if="showPagination">
					<el-pagination
						v-model:current-page="currentPage"
						v-model:page-size="pageSize"
						:page-sizes="pageSizes"
						:total="total"
						:layout="paginationLayout"
						background
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						small
						class="flex justify-center"
					/>
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { Loading, RefreshRight } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fetchList, delObjs } from '/@/api/knowledge/aiMaterialLog';
import { getVideoCompletionStatus } from '/@/api/knowledge/aiGen';
import { Local } from '/@/utils/storage';

export interface HistoryItem {
	id?: string;
	url: string;
	thumbnail: string;
	prompt: string;
	localUrl?: string;
	createTime?: string;
	deleting?: boolean;
	refreshing?: boolean;
	materialStatus?: string;
	originalUrl?: string;
}

const props = defineProps({
	title: {
		type: String,
		default: '历史生成',
	},
	materialType: {
		type: String,
		default: 'Video',
		validator: (value: string) => ['Video', 'Image', 'Audio', 'Text', 'Voice'].includes(value),
	},
	externalItems: {
		type: Array as () => HistoryItem[],
		default: null,
	},
	thumbnailAlt: {
		type: String,
		default: 'Thumbnail',
	},
	emptyText: {
		type: String,
		default: '历史记录为空',
	},
	autoLoad: {
		type: Boolean,
		default: true,
	},
	showTimeColumn: {
		type: Boolean,
		default: true,
	},
	showStatusColumn: {
		type: Boolean,
		default: false,
	},
	showPagination: {
		type: Boolean,
		default: true,
	},
	pageSizes: {
		type: Array as () => number[],
		default: () => [10, 20, 30, 50],
	},
	paginationLayout: {
		type: String,
		default: 'total, sizes, prev, pager, next',
	},
	defaultPageSize: {
		type: Number,
		default: 10,
	},
});

const emit = defineEmits(['item-click', 'update:historyItems']);

// Data
const historyItems = ref<HistoryItem[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(props.defaultPageSize);
const total = ref(0);

// Watch for external items
watch(
	() => props.externalItems,
	(newVal) => {
		if (newVal !== null) {
			historyItems.value = newVal;
			// For external items, set total to the length of the array
			total.value = newVal.length;
		}
	},
	{ immediate: true }
);

// Methods
const handleItemClick = (item: HistoryItem) => {
	emit('item-click', item);
};

const handleDelete = async (item: HistoryItem) => {
	if (!item.id) {
		ElMessage.error('无法删除，记录ID不存在');
		return;
	}

	try {
		// Mark as deleting to show loading state
		item.deleting = true;

		// Confirm before deletion
		await ElMessageBox.confirm('确定要删除这条生成记录吗？', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		});

		// Call the deletion API
		await handleDeleteItem(item.id);
	} catch (error) {
		if (error !== 'cancel') {
			ElMessage.error('删除失败，请稍后重试');
		}
	} finally {
		item.deleting = false;
	}
};

const handleRefreshStatus = async (item: HistoryItem) => {
	if (!item.originalUrl) {
		ElMessage.warning('无法刷新状态，任务ID不存在');
		return;
	}

	try {
		// Mark as refreshing to show loading state
		item.refreshing = true;

		const selectedModel = Local.get(`selectedAiModel:Video`);
		const { data } = await getVideoCompletionStatus(item.originalUrl, selectedModel?.name);

		if (data) {
			if (data.status === 'Succeed' && data.results && data.results.videos && data.results.videos.length > 0) {
				const firstVideo = data.results.videos[0];
				item.url = firstVideo.url;
				item.localUrl = firstVideo.url;
				item.materialStatus = 'Succeed';
				ElMessage.success('视频状态已更新！');

				// 视频更新成功后，触发选中显示
				handleItemClick(item);
			} else if (data.status === 'Failed') {
				const reason = data.reason ? `: ${data.reason}` : '';
				item.materialStatus = 'Failed';
				ElMessage.error(`视频生成失败${reason}`);
			} else {
				item.materialStatus = data.status || item.materialStatus;
				ElMessage.info(`视频状态: ${data.status || '未知'}`);
			}
		}

		refreshHistory();
	} catch (error) {
		ElMessage.error('刷新状态失败，请稍后重试');
	} finally {
		item.refreshing = false;
	}
};

const refreshHistory = async () => {
	// Skip fetching if using external items
	if (props.externalItems !== null) return;

	loading.value = true;
	try {
		const { data } = await fetchList({
			materialType: props.materialType,
			size: pageSize.value,
			current: currentPage.value,
		});
		historyItems.value =
			data.records?.map((record: any) => ({
				id: record.id,
				url: record.localUrl || '',
				thumbnail: record.thumbnail || record.localUrl || '',
				prompt: record.prompt || '',
				localUrl: record.localUrl || '',
				createTime: record.createTime || '',
				materialStatus: record.materialStatus || record.status || '',
				deleting: false,
				refreshing: false,
				originalUrl: record.originalUrl || '',
			})) || [];
		total.value = data.total;
		emit('update:historyItems', historyItems.value);
	} catch (error) {
		ElMessage.error('获取历史记录失败');
	} finally {
		loading.value = false;
	}
};

const handleDeleteItem = async (id: string) => {
	try {
		await delObjs([id]);
		ElMessage.success('删除成功');
		refreshHistory();
	} catch (error) {
		ElMessage.error('删除失败，请稍后重试');
		throw error; // Re-throw for the parent handler
	}
};

// Pagination handlers
const handleSizeChange = (newSize: number) => {
	pageSize.value = newSize;
	refreshHistory();
};

const handleCurrentChange = (newPage: number) => {
	currentPage.value = newPage;
	refreshHistory();
};

// Initialization
onMounted(() => {
	if (props.autoLoad && props.externalItems === null) {
		refreshHistory();
	}
});

// Expose methods and values for parent components
defineExpose({
	refreshHistory,
	handleDeleteItem,
	total,
	currentPage,
	pageSize,
});
</script>